<?php

namespace Modules\Asset\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Asset\Entities\PackageSku;
use Modules\Asset\Entities\PackageOrder as Order;

use Modules\Asset\Entities\AssetOrder;

use Validator;
use ThrowException;
use Auth;
use Setting;
use DB;


// 已开出物品
class PickOrderController extends Controller
{
    // 预览提货订单
    public function preview(Request $req)
    {
        $rule = [
            'package_sku_id' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $item = PackageSku::getEntity([
            'id' => $req->package_sku_id,
            'user_id' => $user->id,
            'with' => ['product.ext', 'product.skus']
        ]);

        $only = [
            'id',
            'uuid',
            'title',
            'sku_type_text',
            'number',
            'thumb',
            'money_price',
            'score_price',
            'total',
            'activity_type',
            // 'return_money',
            // 'return_score',
            // 'return_redpack',
            // 'return_saled_at',
            // 'resaled_at',
            'union_status',
            'union_status_text',
            'sid',
            'product' => [
                'id',
                'uuid',
                'title',
                'sub_title',
                'thumb',
                'tags',
                'number',
                'money_price',
                'score_price',
                'attrs',
                'ext' => [
                    'images',
                    'page',
                    'sku_attrs'
                ],
                'skus' => [
                    '*' => [
                        'id',
                        'uuid',
                        'thumb',
                        'money_price',
                        'score_price',
                        'attrs',
                    ]
                ]
            ]
        ];

        $info = $item->getInfo($only);

        $productInfo = @$info['product'];
        unset($info['product']);

        // 默认地址
        $address = null;
        if ($item->sku_type_text !== 'virtual_asset') {
            $address = $user->addresses()->orderBy('is_default', 'desc')->first();
        }

        $order = [
            'carriage' => 0
        ];

        return [
            'package_sku' => $info,
            'product' => $productInfo,
            'order' => $order,
            'address' => $address
        ];
    }


    // 提交
    public function confirm(Request $req)
    {
        $rule = [
            'package_sku_id' => ['required'],
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        // 奖品
        $packageSku = PackageSku::getEntity([
            'id' => $req->package_sku_id,
            'user_id' => $user->id
        ]);

        // 运费
        $carriage = 0;

        // 优惠券
        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        // 如果是绑定商品
        if ($packageSku->sku_type_text  === 'product') {
            $address = $user->addresses()->where('id', $req->input('address_id'))->first() ?: ThrowException::Conflict('请选择收货地址');

            $packageSku->product || ThrowException::Conflict('此奖品未绑定商品，请联系客服处理~');
            
            // $packageSku->product->isOffStock() && ThrowException::Conflict('此商品已下架，暂无法领取~');
            
            $productSku = $packageSku->product->skus()->where('id', $req->input('product_sku_id'))->first() ?: ThrowException::Conflict('商品sku不存在~');
            // $productSku->isOffStock() && ThrowException::Conflict('此商品规格已下架，请选择其它规格~');

            // $packageSku->attrs = $productSku->attrs;

            $payOrder = $packageSku->pay_order;
            if ($payOrder) {
                $productSku->pay_order_id = $payOrder->id;
                $productSku->pay_order_number = $payOrder->number;
            }

            $skuableMaps = [
                [
                    'skuable' => $productSku,
                    'total' => $packageSku->total
                ]
            ];
            $order = Order::initWith($skuableMaps, $user, $address, [
                'carriage' => $carriage,
                'coupon' => $coupon,
                'is_use_redpack' => 0,
                'options' => [
                ]
            ]);

            // 支付价格置为0
            $order->pay_score_price = 0;
            $order->pay_money_price = 0;
        }
        elseif ($packageSku->sku_type_text  === 'virtual_asset') {

            // 虚拟资产订单发放
            $skuableMaps = [
                [
                    'skuable' => $packageSku,
                    'total' => $packageSku->total
                ]
            ];

            $order = AssetOrder::initWith($skuableMaps, $user, NULL);
        }
        elseif ($packageSku->sku_type_text  === 'custom') {
            ThrowException::Conflict('暂不可提取非商城商品');
        }

        $order->createAll();

        // 标记为提货完成
        $packageSku->pick($order);
        
        return $order->generateResponse();
    }
}
